package com.jiutong.meipengdai.ui.activitys;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jiutong.meipengdai.R;
import com.jiutong.meipengdai.base.BaseActivity;
import com.jiutong.meipengdai.common.Constants;
import com.jiutong.meipengdai.entity.CheckVersionRespond;
import com.jiutong.meipengdai.http.model.interfaces.CheckVersionBiz;
import com.jiutong.meipengdai.http.present.CheckVersionPresent;
import com.jiutong.meipengdai.installapk.DownLoadService;
import com.jiutong.meipengdai.utils.SpConfig;
import com.jiutong.meipengdai.views.dialog.BaseDialog;
import com.orhanobut.logger.Logger;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作用:
 * Created by 78 on 2017/6/15.
 */
public class AboutUsActivity extends BaseActivity implements CheckVersionBiz {

    @Bind(R.id.tv_title)
    TextView tv_title;
    @Bind(R.id.rl_back)
    RelativeLayout rl_back;
    @Bind(R.id.tv_version_code)
    TextView tvVersionCode;
    @Bind(R.id.tv_update)
    TextView tvUpdate;
    @Bind(R.id.iv_loading)
    ImageView ivLoading;
    @Bind(R.id.ll_show_loading)
    LinearLayout ll_show_loading;
    private CheckVersionPresent checkVersionPresent;
    private BaseDialog updateDialog;
    private ApkUpdateDoneBroadcast apkUpdateDoneBroadcast;
    private String upLoadUrl;

    @Override
    public int getLayoutResouceId() {
        return R.layout.activity_aboutus;
    }

    @Override
    protected void initView() {
        super.initView();
        ButterKnife.bind(this);
        tv_title.setText("关于我们");

        try {
            tvVersionCode.setText("版本号  " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
        } catch (Exception e) {
            Logger.e(e.toString());
        }

        checkVersionPresent = new CheckVersionPresent(mContext, this);
        checkVersionPresent.checkVersion();
    }

    @OnClick({R.id.rl_back, R.id.tv_update})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.tv_update:
                showUpdateDailog();
                break;
        }

    }

    @Override
    public void onSuccess(Object object) {

        CheckVersionRespond respond = (CheckVersionRespond) object;
        if (respond.getResCode().equals("200")) {
            upLoadUrl = respond.getData().getLink();
            String latestVersion = respond.getData().getLatestVersion();
            double lastVersion = Double.parseDouble(latestVersion);
            if (lastVersion > getCurrentVersion()) {
                tvUpdate.setVisibility(View.VISIBLE);
                SpConfig.getInstance().putString(Constants.NEWVERSIONURI_STRING, respond.getData().getLink());
            }
        } else {
            toastShortShow(respond.getResDesc());
        }

    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public int getCurrentVersion() {
        try {
            return getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private void showUpdateDailog() {

        if (updateDialog == null) {

            updateDialog = new BaseDialog.Builder().layResuorce(R.layout.dialog_check_version)
                    .okViewClickEvent(R.id.tv_update)
                    .cancelViewClickEvent(R.id.tv_cancel)
                    .animResource(R.style.dialog_animation_fade)
                    .outSideCancel(false)
                    .gravityStyle(Gravity.CENTER)
                    .dialogWidth(-2)
                    .build();

            updateDialog.setOnDialogClickListener(new BaseDialog.OnDialogClickListener() {
                @Override
                public void onOkClick() {
                    updateDialog.dismiss();
                    tvUpdate.setVisibility(View.GONE);
                    ll_show_loading.setVisibility(View.VISIBLE);
                    Glide.with(AboutUsActivity.this).load(R.mipmap.loading).asGif().into(ivLoading);

                    Intent service = new Intent(mContext, DownLoadService.class);
                    service.putExtra(Constants.APKUPLOAD_URL_STRING, upLoadUrl);
                    startService(service);

                    IntentFilter intentFilter = new IntentFilter();
                    intentFilter.addAction("apk_update_done"); //为BroadcastReceiver指定action，即要监听的消息名字。

                    apkUpdateDoneBroadcast = new ApkUpdateDoneBroadcast();
                    registerReceiver(apkUpdateDoneBroadcast, intentFilter); //注册监听
                }

                @Override
                public void onOk2Click() {

                }
            });
        }

        updateDialog.show(getSupportFragmentManager(), TAG);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (apkUpdateDoneBroadcast != null)
            unregisterReceiver(apkUpdateDoneBroadcast); //取消监听
    }

    public class ApkUpdateDoneBroadcast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ll_show_loading.setVisibility(View.GONE);
        }
    }
}
